#-*- coding: utf-8 -*-

# Create your views here.
from pieceup.blog.models import Blog
from pieceup.blog.models import Category
from pieceup.blog.models import Message
from pieceup.blog.models import Comment
from pieceup.blog.models import Link
from pieceup.blog.models import Maxim

import datetime
import random

from django.template import Context, loader
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render_to_response
from django.core.paginator import Paginator


imageURL = '/site_media/pictures/'
imageList = [id for id in range(1, 17)]


def index(request):
    """首页
    """
    randImage = getRandomImage()
    
        
    
    blog_entry = Blog.objects.all().order_by('-pub_date')
    latest_entry = blog_entry[:5]
    my_link = Link.objects.all()
    maxim = getRandomMaxim()
    
    #取分类显示Blog
    if request.GET.get('category', 'noCategory') != 'noCategory':
        whichCategory = int(request.GET['category'])
        blog_entry = Blog.objects.filter(category = whichCategory).order_by('-pub_date')

    #分页处理，每页显示5项
    pages = Paginator(blog_entry, 10)
    curPage = int(request.GET.get('page', '1'))
    myCategory = Category.objects.all()
    
    #取当前页的Blog文章
    blogs = pages.page(curPage)
    comment = Comment.objects.all().order_by('-pub_date')[:10]
    t = loader.get_template('blog/index.html')
    c = Context({\
            'maxim': maxim,\
            'randImage': randImage,\
            'latestEntry': blogs.object_list,\
            'navLatestEntry': latest_entry,\
            'category': myCategory,\
            'comments': comment,\
            'links': my_link,\
            'is_paginator': pages.num_pages > 1,\
            'has_next': blogs.has_next(),\
            'has_previous': blogs.has_previous(),\
            'page_range': pages.page_range,\
            'cur_page': curPage,\
            'next_page': curPage + 1,\
            'previous_page': curPage - 1,\
            'end_page': pages.num_pages,\
            })
    return HttpResponse(t.render(c))

def message(request):
    """留言版
    """
    randImage = getRandomImage()
    maxim = getRandomMaxim()
    #取分类显示Blog
    if request.GET.get('category', 'noCategory') != 'noCategory':
        whichCategory = request.GET['category']
        return HttpResponseRedirect('/blog/?category=%s' %whichCategory)
    
    category = Category.objects.all()
    message = Message.objects.all().order_by('-pub_date')
    #获取session中的名字
    userName = request.session.get('userName', None)
    if userName:
        name = userName
    else:
        name = ''
    
    t = loader.get_template('blog/message.html')
    c = Context({\
            'maxim': maxim,\
            'randImage': randImage,\
            'category': category,\
            'message': message,\
            'myName': name,\
            'errorMessage': '',\
            })
    return HttpResponse(t.render(c))

def aboutMe(request):
    """关于我
    """
    #取分类显示Blog
    if request.GET.get('category', 'noCategory') != 'noCategory':
        whichCategory = request.GET['category']
        return HttpResponseRedirect('/blog/?category=%s' %whichCategory)
    
    randImage = getRandomImage()
    maxim = getRandomMaxim()
    category = Category.objects.all()
    return render_to_response('blog/aboutMe.html',
                              {\
                               'maxim': maxim,\
                               'category': category,\
                               'randImage': randImage,\
                                      })


def leaveMessage(request):
    """提交留言版
    """
    #取分类显示Blog
    if request.GET.get('category', 'noCategory') != 'noCategory':
        whichCategory = request.GET['category']
        return HttpResponseRedirect('/blog/?category=%s' %whichCategory)
    
    category = Category.objects.all()
    randImage = getRandomImage()
    message = Message.objects.all().order_by('-pub_date')
    userName = request.POST['name']
    userMail = request.POST['email']
    userWebAddress = request.POST['url']
    userMessage = request.POST['message']
    rememberMe = request.POST['remember']

    if userName == '':
        return render_to_response('blog/message.html',
                                  {'message': message,\
                                   'randImage': randImage,\
                                   'category': category,\
                                   'myMessage': userMessage,\
                                   'noName': '请输入您的姓名...',\
                                          })
    elif userMessage == '':
        return render_to_response('blog/message.html',
                                  {'message': message,\
                                   'randImage': randImage,\
                                   'category': category,\
                                   'myName': userName,\
                                   'noMessage': '请输入留言...',\
                                          })
    else:
        if rememberMe == 'yes':
            request.session['userName'] = userName
        message = Message()
        message.name = userName
        if userMail == '':
            message.email = 'example@bin.com'
        else:
            message.email = userMail
        if userWebAddress == '':
            message.webAddress = 'example.com'
        else:
            message.webAddress = userWebAddress
        message.message = userMessage
        message.pub_date = datetime.datetime.now()
        message.save()
    return HttpResponseRedirect('/blog/message/')

def showBlog(request, blogId):
    """显示Blog全文
    
    Arguments:
    - `request`:
    - `blogId`:
    """

    #取分类显示Blog
    if request.GET.get('category', 'noCategory') != 'noCategory':
        whichCategory = request.GET['category']
        return HttpResponseRedirect('/blog/?category=%s' %whichCategory)
        
    category = Category.objects.all()
    randImage = getRandomImage()
    maxim = getRandomMaxim()
    blog = get_object_or_404(Blog, pk = blogId)
    comment = blog.comment_set.all().order_by('-pub_date')

    userName = request.session.get('userName', None)
    if userName:
        name = userName
    else:
        name = ''
    
    return render_to_response('blog/showBlog.html',
                              {'randImage': randImage,\
                               'maxim': maxim,\
                               'category': category,\
                               'selectedBlog': blog,\
                               'comment': comment,\
                               'myName': name,\
                                      })

                                      
def leaveComment(request):
    """提交Blog评论
    
    Arguments:
    - `request`:
    """
    #取分类显示Blog
    if request.GET.get('category', 'noCategory') != 'noCategory':
        whichCategory = request.GET['category']
        return HttpResponseRedirect('/blog/?category=%s' %whichCategory)

    category = Category.objects.all()
    randImage = getRandomImage()
    blogId = request.POST['blogId']
    blog = get_object_or_404(Blog, pk = blogId)
    comment = blog.comment_set.all().order_by('-pub_date')
    userName = request.POST['name']
    userMail = request.POST['email']
    userWebAddress = request.POST['url']
    userMessage = request.POST['message']
    rememberMe = request.POST['remember']
        
    if userName == '':
        return render_to_response('blog/showBlog.html',
                                  {'randImage': randImage,\
                                   'category': category,\
                                   'selectedBlog': blog,\
                                   'comment': comment,\
                                   'myMessage': userMessage,\
                                   'myMail': userMail,\
                                   'myWeb': userWebAddress,\
                                   'noName': '请输入您的姓名...',\
                                          })
    elif userMessage == '':
        return render_to_response('blog/showBlog.html',
                                  {'randImage': randImage,\
                                   'category': category,\
                                   'selectedBlog': blog,\
                                   'comment': comment,\
                                   'myName': userName,\
                                   'myMail': userMail,\
                                   'myWeb': userWebAddress,\
                                   'noMessage': '请输入留言...',\
                                          })
    else:
        if rememberMe == 'yes':
            request.session['userName'] = userName
#         else:
#             # 如果选不记住，则尝试清除session 但是似乎没有这个必要？...
#             try:
#                 del request.session['userName']
#             except:
#                 pass
            
        comment = Comment(blog_id = blogId)
        comment.name = userName
        if userMail == '':
            comment.email = 'example@bin.com'
        else:
            comment.email = userMail
        if userWebAddress == '':
            comment.webAddress = 'example.com'
        else:
            comment.webAddress = userWebAddress
        comment.comment = userMessage
        comment.pub_date = datetime.datetime.now()
        comment.save()
    return HttpResponseRedirect(reverse('pieceup.blog.views.showBlog', args = (blogId)))

                                      
def getRandomImage():
    """获取随机的封面图片
    """
    imageId = random.choice(imageList)
    return imageURL + str(imageId) + '.jpg'

def getRandomMaxim():
    """获取随机箴言
    """
    maxims = Maxim.objects.all()
    maxim = random.choice(maxims)
    return maxim
